package crawler;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import utility.dates.MDate;
import utility.files.TextFile;

public class StatisticsFileWriter {
	private static StatisticsFileWriter _instance;
	private TextFile _file;
	private Map<String,Long> _crawlerToMaxLinks;
	private Map<String,Long> _crawlerToCurrentLinks;

	private StatisticsFileWriter() {
		String path = "./";
		validate(path);
		_crawlerToMaxLinks = new HashMap<String,Long>();
		_crawlerToCurrentLinks = new HashMap<String,Long>();
	}
	
	public synchronized static StatisticsFileWriter getInstance(){
		if(_instance==null) _instance = new StatisticsFileWriter();
		return _instance;
	}
	
	public void setPath(String path){
		validate(path);
	}

	private void validate(String path) {
		File file = new File(path);
		if(!file.isDirectory()) file = new File(file.getParent());
		
		_file = TextFile.inRewrite(file+"/statistics.txt");
	}

	public void register(String crawlerName, long maxLinks) {
		_crawlerToMaxLinks.put(crawlerName, maxLinks);
		_crawlerToCurrentLinks.put(crawlerName, (long)0);
	}

	public synchronized void add(String crawlerName, int linksToAdd) {
		if(_crawlerToCurrentLinks.get(crawlerName)==null) return;
		
		long totalLinks = _crawlerToCurrentLinks.get(crawlerName) + linksToAdd;
		_crawlerToCurrentLinks.put(crawlerName, totalLinks);
		_file.putLine(MDate.now().asDottedString(false)+"  "+crawlerName+" -----> "+totalLinks+" links found");
	}

}
